import { notification } from 'antd'
import axios from 'axios'
import { useEffect ,useState} from 'react'
function usePublish(type){
    const [dataSource, setdataSource] = useState([])
    
    const { username}=JSON.parse(localStorage.getItem("token"))
    useEffect(()=>{
        axios.get(`/news?author=${username}&publishState=${type}&_expand=category`).then(res=>{
            setdataSource(res.data)
        })

    },[username,type])
    const handlePublish=(id)=>{
        setdataSource(dataSource.filter(item=>item.id!==id))
        axios.patch(`/news/${id}`,{
            publishState:2,
            publishTime:Date.now()
        }).then(res=>{
            notification.info({
                message:`通知`,
                description:`您可以到【已发布】中查看您的新闻`,
                placement:'bottomRight'

            })
        })
    }
    const handleSunset=(id)=>{
        setdataSource(dataSource.filter(item=>item.id!==id))
        axios.patch(`/news/${id}`,{
            publishState:3,
            publishTime:Date.now()
        }).then(res=>{
            notification.info({
                message:`通知`,
                description:`您可以到【已下线】中查看您的新闻`,
                placement:'bottomRight'

            })
        })
    }
    const handleDelete=(id)=>{
        setdataSource(dataSource.filter(item=>item.id!==id))
        axios.delete(`/news/${id}`).then(res=>{
            notification.info({
                message:`通知`,
                description:`您已经删除了已下线的新闻`,
                placement:'bottomRight'

            })
        })
    }
    return {dataSource,handleDelete,handlePublish,handleSunset}
}
export default usePublish